<?php

/**
 * [fnCheckPhone 验证是否是手机号]
 * @author limx
 * @param $phonenumber 手机号码
 * @return bool
 */
function fnCheckPhone($phonenumber){
    if(preg_match("/^1[34578]{1}\d{9}$/",$phonenumber)){
        return true;
    }
    return false;
}

/**
 * [fnObjectArray stdClass Object 转 array]
 * @author limx
 * @param $array stdClass Objec
 * @return array
 */
function fnObjectToArray($array){
    if(is_object($array)){
        $array = (array)$array;
    }
    if(is_array($array)){
        foreach($array as $key=>$value){
            $array[$key] = fnObjectToArray($value);
        }
    }
    return $array;
}

/**
 * [fnGetRandomString 获取随机字符串]
 * @author limx
 * @param $intLength 字符串长度
 * @param string $strType 类型
 * @return string
 */
function fnGetRandomString($intLength, $strType = 'C')
{
    $arrChars = array();
    if ($strType == "N") {//获取数字随机码
        $arrChars = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    } else if ($strType == "S") {//获取字母随机码
        $arrChars = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
    } else if ($strType == "C") {//获取数字+字母随机码
        $arrChars = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    }
    $intCharsLen = count($arrChars) - 1;
    shuffle($arrChars);
    // 将数组打乱
    $strOutput = "";
    for ($i = 0; $i < $intLength; $i++) {
        $strOutput .= $arrChars[mt_rand(0, $intCharsLen)];
        //获得一个数组元素
    }
    return $strOutput;
}

/**
 * [fnGetUserID 获取Session 的UserID]
 * @Author   Limx
 * @Method   直接调用
 * @DateTime 2016-02-29T15:29:16+0800
 * @return   [type]                   [description]
 */
function fnGetUserID()
{
    return $_SESSION["UserID"];
}

/**
 * [fnGetUrl 获取当前Url]
 * @Author   Limx
 * @Method   直接调用
 * @DateTime 2016-02-24T15:07:32+0800
 * @return   [type]                   [description]
 */
function fnGetUrl()
{

    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;

}

/**
 * [fnGetNowTime 获取当前时间]
 * @Author   Limx
 * @Method   直接调用
 * @DateTime 2016-02-19T22:32:56+0800
 * @return   [type]                   [description]
 */
function fnGetNowTime()
{
    return Date("Y-m-d H:i:s");
}

/**
 * [imgpress 调整图片尺寸或生成缩略图 返回:True/False]
 * @Author   Limx
 * @Method   直接调用
 * @DateTime 2015-12-04T16:04:05+0800
 * @param    [type]                   $Image [需要调整的图片(含路径)]
 * @param    integer $Dw [调整时最大宽度;缩略图时的绝对宽度]
 * @param    integer $Dh [调整时最大高度;缩略图时的绝对高度]
 * @param    integer $Type [1,调整尺寸; 2,生成缩略图]
 * @return   [type]                          [description]
 */
function lfnImgpress($Image, $Dw = 450, $Dh = 450, $Type = 1)
{
    IF (!File_Exists($Image)) {
        Return False;
    }// 如果需要生成缩略图,则将原图拷贝一下重新给$Image赋值
    IF ($Type != 1) {
        Copy($Image, Str_Replace(".", "_x.", $Image));
        $Image = Str_Replace(".", "_x.", $Image);
    }// 取得文件的类型,根据不同的类型建立不同的对象
    $ImgInfo = GetImageSize($Image);
    Switch ($ImgInfo[2]) {
        Case 1 :
            $Img = @ImageCreateFromGIF($Image);
            Break;
        Case 2 :
            $Img = @ImageCreateFromJPEG($Image);
            Break;
        Case 3 :
            $Img = @ImageCreateFromPNG($Image);
            Break;
    }// 如果对象没有创建成功,则说明非图片文件
    IF (Empty($Img)) {// 如果是生成缩略图的时候出错,则需要删掉已经复制的文件
        IF ($Type != 1) {
            Unlink($Image);
        }
        Return False;
    }// 如果是执行调整尺寸操作则
    IF ($Type == 1) {
        $w = ImagesX($Img);
        $h = ImagesY($Img);
        $width = $w;
        $height = $h;
        IF ($width > $Dw) {
            $Par = $Dw / $width;
            $width = $Dw;
            $height = $height * $Par;
            IF ($height > $Dh) {
                $Par = $Dh / $height;
                $height = $Dh;
                $width = $width * $Par;
            }
        } ElseIF ($height > $Dh) {
            $Par = $Dh / $height;
            $height = $Dh;
            $width = $width * $Par;
            IF ($width > $Dw) {
                $Par = $Dw / $width;
                $width = $Dw;
                $height = $height * $Par;
            }
        } else {
            $width = $width;
            $height = $height;
        }
        $nImg = ImageCreateTrueColor($width, $height);
        // 新建一个真彩色画布
        ImageCopyReSampled($nImg, $Img, 0, 0, 0, 0, $width, $height, $w, $h);
        // 重采样拷贝部分图像并调整大小
        ImageJpeg($nImg, $Image);
        // 以JPEG格式将图像输出到浏览器或文件
        Return True;
        // 如果是执行生成缩略图操作则
    } else {
        $w = ImagesX($Img);
        $h = ImagesY($Img);
        $width = $w;
        $height = $h;
        $nImg = ImageCreateTrueColor($Dw, $Dh);
        IF ($h / $w > $Dh / $Dw) {// 高比较大
            $width = $Dw;
            $height = $h * $Dw / $w;
            $IntNH = $height - $Dh;
            ImageCopyReSampled($nImg, $Img, 0, -$IntNH / 1.8, 0, 0, $Dw, $height, $w, $h);
        } else {// 宽比较大
            $height = $Dh;
            $width = $w * $Dh / $h;
            $IntNW = $width - $Dw;
            ImageCopyReSampled($nImg, $Img, -$IntNW / 1.8, 0, 0, 0, $width, $Dh, $w, $h);
        }
        ImageJpeg($nImg, $Image);
        Return True;
    }
}

/**
 * [getSignature 使用HMAC-SHA1算法生成签名]
 * @Author   Limx
 * @Method   直接使用base64_encode(hash_hmac("sha1", $str, $key, true));
 * @DateTime 2015-12-12T21:18:05+0800
 * @param    [type]                   $str [description]
 * @param    [type]                   $key [secret&]
 * @return   [type]                        [description]
 */
function getSignature($str, $key)
{
    $signature = "";
    if (function_exists('hash_hmac')) {
        $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
    } else {
        $blocksize = 64;
        $hashfunc = 'sha1';
        if (strlen($key) > $blocksize) {
            $key = pack('H*', $hashfunc($key));
        }
        $key = str_pad($key, $blocksize, chr(0x00));
        $ipad = str_repeat(chr(0x36), $blocksize);
        $opad = str_repeat(chr(0x5c), $blocksize);
        $hmac = pack('H*', $hashfunc(($key ^ $opad) . pack('H*', $hashfunc(($key ^ $ipad) . $str))));
        $signature = base64_encode($hmac);
    }
    return $signature;
}

/**
 * [ufnCheckInts 正则匹配id字符串]
 * @Author   Limx
 * @Method   直接调用
 * @DateTime 2015-12-04T10:50:43+0800
 * @param    string $strId [id,id,id]
 * @return   [type]                          [description]
 */
function fnCheckInts($ids = "")
{
    $reg = "/^([0-9]+,)*[0-9]+$/";
    if (preg_match($reg, $ids)) {
        return true;
    }
    return false;
}

/**
 * 通过CURL发送HTTP请求
 * @param string $url //请求URL
 * @param array $postFields //请求参数
 * @return mixed
 */
function curlPost($url, $postFields)
{

    $postFields = http_build_query($postFields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

/**
 * [curlPostCookies 通过CURL发送HTTP POST请求]
 * @Author   Limx
 * @Method   直接调用
 * @DateTime 2016-01-01T21:22:44+0800
 * @param    [type]                   $url        [目标地址]
 * @param    [type]                   $postFields [post数据]
 * @param    [type]                   $cookies    [携带的cookie数据]
 * @return   [type]                               [请求返回的内容]
 */
function curlPostCookies($url, $postFields, $cookies)
{
    $postFields = http_build_query($postFields);
    $cookies_string = '';
    foreach ($cookies as $name => $value) {
        $cookies_string .= $name . '=' . $value . ';';
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_COOKIE, $cookies_string);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function curlGet($url)
{

    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //执行命令
    $result = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);

    return $result;
}

/**
 * 系统邮件发送函数
 * @param string $to 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null)
{
    $config = C('THINK_EMAIL');
    Vendor('PHPMailer.class#phpmailer');
    //从PHPMailer目录导class.phpmailer.php类文件
    Vendor('PHPMailer.class#smtp');
    $mail = new PHPMailer();
    //PHPMailer对象
    $mail->CharSet = 'UTF-8';
    //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();
    // 设定使用SMTP服务
    $mail->SMTPDebug = 1;
    // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth = true;
    // 启用 SMTP 验证功能
    // if($config['SMTP_PORT'] != 25){
    //     $mail->SMTPSecure = 'ssl';             // 使用安全协议
    // }
    $mail->SMTPSecure = 'ssl';
    $mail->Host = gethostbyname($config['SMTP_HOST']);
    // SMTP 服务器
    $mail->Port = $config['SMTP_PORT'];
    // SMTP服务器的端口号
    $mail->Username = $config['SMTP_USER'];
    // SMTP服务器用户名
    $mail->Password = $config['SMTP_PASS'];
    // SMTP服务器密码
    //$mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    //$mail->SetFrom($config['FROM_EMAIL'], "=?GBK?B?".base64_encode($config['FROM_NAME'])."?=");

    $mail->From = $config['FROM_EMAIL'];
    $mail->FromName = $config['FROM_NAME'];
    $replyEmail = $config['REPLY_EMAIL'] ? $config['REPLY_EMAIL'] : $config['FROM_EMAIL'];
    $replyName = $config['REPLY_NAME'] ? $config['REPLY_NAME'] : $config['FROM_NAME'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if (is_array($attachment)) {// 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/*
 * 发送邮件
 * build by limx 2015-11-19
 */

function sendMail($to, $title, $content)
{

    //Vendor('PHPMailer.PHPMailerAutoload');
    Vendor('PHPMailer.class#phpmailer');
    Vendor('PHPMailer.class#smtp');
    $mail = new PHPMailer();
    //实例化
    $mail->IsSMTP();
    // 启用SMTP
    $mail->Host = C('MAIL_HOST');
    //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth = C('MAIL_SMTPAUTH');
    //启用smtp认证
    $mail->Username = C('MAIL_USERNAME');
    //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD');
    //邮箱密码
    $mail->From = C('MAIL_FROM');
    //发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME');
    //发件人姓名
    $mail->AddAddress($to, "尊敬的客户");
    $mail->WordWrap = 50;
    //设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML'));
    // 是否HTML格式邮件
    $mail->CharSet = C('MAIL_CHARSET');
    //设置邮件编码
    $mail->Subject = $title;
    //邮件主题
    $mail->Body = $content;
    //邮件内容
    $mail->SMTPDebug = 1;
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端";
    //邮件正文不支持HTML的备用显示
    return ($mail->Send());
}

/**
 * @blog<http://www.phpddt.com>
 */

function listDir($dir)
{
    $dir .= substr($dir, -1) == '/' ? '' : '/';
    $dirInfo = array();
    foreach (glob($dir . '*') as $v) {
        $dirInfo[] = $v;
        if (is_dir($v)) {
            $dirInfo = array_merge($dirInfo, listDir($v));
        }
    }
    return $dirInfo;
}

function is_mobile()
{
    $user_agent = $_SERVER["HTTP_USER_AGENT"];
    $mobile_agents = array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "iphone", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");

    $is_mobile  =  false;
    for ($i = 0; $i < count($mobile_agents); $i++) {
        if (stristr($user_agent, $mobile_agents[$i])) {
            $is_mobile  = true;
            break;
        }
    }
    return $is_mobile ;
}

/*
 * 获取当前时间
 */
function now()
{
    return Date("y-m-d h:i:s");
}

/**
 * TODO 基础分页的相同代码封装，使前台的代码更少
 *
 * @param $m 模型，引用传递
 * @param $where 查询条件
 * @param int $pagesize
 *            每页查询条数
 * @return \Think\Page
 */
function getpage(&$m, $where, $pagesize = 10)
{
    $m1 = clone $m;
    // 浅复制一个模型
    $count = $m->where($where)->count();
    // 连惯操作后会对join等操作进行重置
    $m = $m1;
    // 为保持在为定的连惯操作，浅复制一个模型
    $p = new Think\Page($count, $pagesize);
    $p->lastSuffix = false;
    $p->setConfig('header', '<li>共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;每页<b>%LIST_ROW%</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
    $p->setConfig('prev', '上一页');
    $p->setConfig('next', '下一页');
    $p->setConfig('last', '末页');
    $p->setConfig('first', '首页');
    // $p->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
    $p->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');

    $p->parameter = I('get.');

    $m->limit($p->firstRow, $p->listRows);

    return $p;
}

/**
 * 导出数据为excel表格
 *
 * @param $data 一个二维数组,结构如同从数据库查出来的数组
 * @param $title excel的第一行标题,一个数组,如果为空则没有标题
 * @param $filename 下载的文件名
 * @examlpe
 *            $stu = M ('User');
 *            $arr = $stu -> select();
 *            exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
 */
function exportexcel($data = array(), $title = array(), $filename = 'report')
{
    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:attachment;filename=" . $filename . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    // 导出xls 开始
    if (!empty($title)) {
        foreach ($title as $k => $v) {
            $title[$k] = iconv("UTF-8", "GB2312", $v);
        }
        $title = implode("\t", $title);
        echo "$title\n";
    }
    if (!empty($data)) {
        foreach ($data as $key => $val) {
            foreach ($val as $ck => $cv) {
                $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
            }
            $data[$key] = implode("\t", $data[$key]);
        }
        echo implode("\n", $data);
    }
}

/**
 * * desription 压缩图片 *
 *
 * @param sting $imgsrc
 *            图片路径 *
 * @param string $imgdst
 *            压缩后保存路径
 *
 */
function image_png_size_add($imgsrc, $imgdst)
{
    list($width, $height, $type) = getimagesize($imgsrc);
    $new_width = ($width > 600 ? 600 : $width) * 0.9;
    $new_height = ($height > 600 ? 600 : $height) * 0.9;
    switch ($type) {
        case 1 :
            $giftype = check_gifcartoon($imgsrc);
            if ($giftype) {
                header('Content-Type:image/gif');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromgif($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
            }
            break;
        case 2 :
            header('Content-Type:image/jpeg');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_wp, $imgdst, 75);
            imagedestroy($image_wp);
            break;
        case 3 :
            header('Content-Type:image/png');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefrompng($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_wp, $imgdst, 75);
            imagedestroy($image_wp);
            break;
    }
}

/*
 * 函数:调整图片尺寸或生成缩略图 返回:True/False
 * 参数: $Image 需要调整的图片(含路径)
 * $Dw=450 调整时最大宽度;缩略图时的绝对宽度
 * $Dh=450 调整时最大高度;缩略图时的绝对高度
 * $Type=1 1,调整尺寸; 2,生成缩略图
 */
Function imgpress($Image, $Dw = 450, $Dh = 450, $Type = 1)
{
    IF (!File_Exists($Image)) {
        Return False;
    }// 如果需要生成缩略图,则将原图拷贝一下重新给$Image赋值
    IF ($Type != 1) {
        Copy($Image, Str_Replace(".", "_x.", $Image));
        $Image = Str_Replace(".", "_x.", $Image);
    }// 取得文件的类型,根据不同的类型建立不同的对象
    $ImgInfo = GetImageSize($Image);
    Switch ($ImgInfo[2]) {
        Case 1 :
            $Img = @ImageCreateFromGIF($Image);
            Break;
        Case 2 :
            $Img = @ImageCreateFromJPEG($Image);
            Break;
        Case 3 :
            $Img = @ImageCreateFromPNG($Image);
            Break;
    }// 如果对象没有创建成功,则说明非图片文件
    IF (Empty($Img)) {// 如果是生成缩略图的时候出错,则需要删掉已经复制的文件
        IF ($Type != 1) {
            Unlink($Image);
        }
        Return False;
    }// 如果是执行调整尺寸操作则
    IF ($Type == 1) {
        $w = ImagesX($Img);
        $h = ImagesY($Img);
        $width = $w;
        $height = $h;
        IF ($width > $Dw) {
            $Par = $Dw / $width;
            $width = $Dw;
            $height = $height * $Par;
            IF ($height > $Dh) {
                $Par = $Dh / $height;
                $height = $Dh;
                $width = $width * $Par;
            }
        } ElseIF ($height > $Dh) {
            $Par = $Dh / $height;
            $height = $Dh;
            $width = $width * $Par;
            IF ($width > $Dw) {
                $Par = $Dw / $width;
                $width = $Dw;
                $height = $height * $Par;
            }
        } else {
            $width = $width;
            $height = $height;
        }
        $nImg = ImageCreateTrueColor($width, $height);
        // 新建一个真彩色画布
        ImageCopyReSampled($nImg, $Img, 0, 0, 0, 0, $width, $height, $w, $h);
        // 重采样拷贝部分图像并调整大小
        ImageJpeg($nImg, $Image);
        // 以JPEG格式将图像输出到浏览器或文件
        Return True;
        // 如果是执行生成缩略图操作则
    } else {
        $w = ImagesX($Img);
        $h = ImagesY($Img);
        $width = $w;
        $height = $h;
        $nImg = ImageCreateTrueColor($Dw, $Dh);
        IF ($h / $w > $Dh / $Dw) {// 高比较大
            $width = $Dw;
            $height = $h * $Dw / $w;
            $IntNH = $height - $Dh;
            ImageCopyReSampled($nImg, $Img, 0, -$IntNH / 1.8, 0, 0, $Dw, $height, $w, $h);
        } else {// 宽比较大
            $height = $Dh;
            $width = $w * $Dh / $h;
            $IntNW = $width - $Dw;
            ImageCopyReSampled($nImg, $Img, -$IntNW / 1.8, 0, 0, 0, $width, $Dh, $w, $h);
        }
        ImageJpeg($nImg, $Image);
        Return True;
    }
}

/**
 * * desription 判断是否gif动画 * @param sting $image_file图片路径 * @return boolean t 是 f 否
 */
function check_gifcartoon($image_file)
{
    $fp = fopen($image_file, 'rb');
    $image_head = fread($fp, 1024);
    fclose($fp);
    return preg_match("/" . chr(0x21) . chr(0xff) . chr(0x0b) . 'NETSCAPE2.0' . "/", $image_head) ? false : true;
}

/*
 * uploadfile()
 * @param path 路径
 */
function upfileimg($path, $phtypes, $imgname, $ext = "")
{
    $check = true;

    if (!is_uploaded_file($_FILES[$imgname][tmp_name])) {
        $msg = "0";
        // 不存在
        $check = false;
    }
    if (!is_dir($path)) {
        // 路径若不存在则创建
        // mkdir($path);//只能新建一层
        mkdir($path, 0777, true);
        // 多层
    }

    $upfile = $_FILES[$imgname];

    if (in_array($upfile["type"], $phtypes) && $check) {
        $msg = "1";
        // 类型不符
        $check = false;
    }

    if ($check) {
        $pinfo = pathinfo($upfile["name"]);
        $name = $pinfo['basename'];
        // 文件名
        $tmp_name = $upfile["tmp_name"];
        $file_type = $pinfo['extension'];
        // 获得文件类型

        $showphpath = $path . $name;

        $timename = Date("ymdhis") . $ext . "." . $file_type;
        $tmp_img_name = $path . $timename;
        $showphpath = $tmp_img_name;
        if (move_uploaded_file($tmp_name, $showphpath)) {
            $msg = $timename;
        }
    }

    return $msg;
}
